//
//  ConvenientPayFinishInfoController.m
//  HuLaQuan
//
//  Created by hok on 2/5/16.
//  Copyright © 2016 yuwubao. All rights reserved.
//

#import "ConvenientPayFinishInfoController.h"

#import "ZCTradeView.h"

//Logic Modal
#import "ConvenientPayConfirmEngine.h"
#import "VerifyPayPasswordEngine.h"
#import "GetUserDetailInfoEngine.h"

//Utility
#import "YuUserDefaultsUtilities.h"

//Jump Back
//#import "ConvenientPayViewController.h"
#import "BalanceHomeViewController.h"

@interface ConvenientPayFinishInfoController ()<ZCTradeViewDelegate>

@property (nonatomic,strong) ZCTradeView *tradeView;



@property (nonatomic,strong)  ConvenientPayConfirmEngine *convenientPayConfirmEngine;

@property (nonatomic, strong) VerifyPayPasswordEngine *verifyPayPasswordEngine;

@property (nonatomic, strong) GetUserDetailInfoEngine *getUserDetailInfoEngine;

@end

@implementation ConvenientPayFinishInfoController

- (GetUserDetailInfoEngine *)getUserDetailInfoEngine
{
    if (!_getUserDetailInfoEngine) {
        _getUserDetailInfoEngine = [[GetUserDetailInfoEngine alloc] init];
    }
    return _getUserDetailInfoEngine;
}

- (ConvenientPayConfirmEngine *)convenientPayConfirmEngine
{
    if (!_convenientPayConfirmEngine) {
        _convenientPayConfirmEngine = [[ConvenientPayConfirmEngine alloc] init];
    }
    return _convenientPayConfirmEngine;
}
- (VerifyPayPasswordEngine *)verifyPayPasswordEngine
{
    if (!_verifyPayPasswordEngine) {
        _verifyPayPasswordEngine = [[VerifyPayPasswordEngine alloc] init];
    }
    return _verifyPayPasswordEngine;
}

#pragma mark - Setup
- (void)updateUI
{
    self.showPayment.text = [NSString stringWithFormat:@"¥%@",ServerMoneyFloatToShow(self.orderInfo[@"payAmt"])] ;
    self.payName.text = self.orderInfo[@"resName"];
    
    self.userCardList = self.cardList;
    
    self.payCompany.text = self.companyName;
    
    
    self.selectedPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self.payTableView selectRowAtIndexPath:self.selectedPath animated:NO scrollPosition:UITableViewScrollPositionTop];
    
    //NSLog(@"%@",self.userCardList);
}
#pragma mark - Button Events
-(void)tapPayButton
{
    NSString *payAmount = self.orderInfo[@"payAmt"];
    NSString *value = ServerMoneyToShow(payAmount);
    NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
    if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        [self.convenientPayConfirmEngine payConvenientOrderwithCard:self.cardList[self.selectedPath.row - 1]];
    }else if(!limit.length){
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserDetailInfoEngine getUserInfo];
    }else{
        self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
        self.tradeView.delegate = self;
        [self.tradeView showInView:self.view];
    }
    
}
- (void)changeCard
{
    if(self.orderInfo && self.cardList.count)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.convenientPayConfirmEngine getPaymentInfo:self.cardList[self.selectedPath.row - 1] andOrderInfo:self.orderInfo];
        
        
    }

}
-(NSString *)finish:(NSString *)pwd{
    NSLog(@"haha %@",pwd);
    
    // [self.passwordAndInfos setObject:pwd forKey:@"checkpassword"];
    
    
    return pwd;
}
-(NSString *)finish:(NSString *)pwd confirm:(BOOL)isConfirm
{
    [self.tradeView cancle];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.verifyPayPasswordEngine verifyPayPassword:pwd];
//    self.shadowView.hidden = NO;
//    self.finishView.hidden = NO;
//    NSTimer *timerCount = [NSTimer scheduledTimerWithTimeInterval:2
//                                                           target:self
//                                                         selector:@selector(timerForExit:)
//                                                         userInfo:nil
//                                                          repeats:NO];
//    [[NSRunLoop currentRunLoop] addTimer:timerCount
//                                 forMode:NSRunLoopCommonModes];
    return pwd;
}

- (void)timerForExit:(NSTimer *)timer
{
    self.shadowView.hidden = YES;
    self.finishView.hidden = YES;
    
    [timer invalidate];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}




#pragma mark - CallBack

- (void)getConvenientPaymentInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSLog(@"支付信息确认成功");
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

//验证支付密码回调
- (void)verifyPayPasswordFinish:(NSNotification*) notification
{
    
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        [self.convenientPayConfirmEngine payScanOrder:messageDic[@"result"] withCard:self.cardList[self.selectedPath.row - 1]];
    }else{
        [YuNetworkStatusUtilities dismissHUD];
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}//支付订单回调
- (void)payConvenientOrderFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSLog(@"%@",messageDic[@"result"])
        //self.paymentFinishInfo = messageDic[@"result"];
        
        
            self.shadowView.hidden = NO;
            self.finishView.hidden = NO;
            NSTimer *timerCount = [NSTimer scheduledTimerWithTimeInterval:2
                                                                   target:self
                                                                 selector:@selector(timerForExit:)
                                                                 userInfo:nil
                                                                  repeats:NO];
            [[NSRunLoop currentRunLoop] addTimer:timerCount
                                         forMode:NSRunLoopCommonModes];
        
//        UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"成功支付订单" andBlock:^(UIAlertAction *action ) {
//            if ([action.title isEqualToString:@"好的"]) {
//                // [self.navigationController popToRootViewControllerAnimated:YES];
//                
//                [self performSegueWithIdentifier:@"ShowPayFinishFromScan" sender:self];
//                
//            }
//            
//        }  type:@"confirm"];
//        [self presentViewController:x animated:YES completion:nil];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSString *payAmount = self.orderInfo[@"payAmt"];
        NSString *value = ServerMoneyToShow(payAmount);
        NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
        if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
        {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            
            [self.convenientPayConfirmEngine payConvenientOrderwithCard:self.cardList[self.selectedPath.row - 1]];
        }else{
            self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
            self.tradeView.delegate = self;
            [self.tradeView showInView:self.view];
        }
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
#pragma mark - Navigation

- (void)goBackAction
{
    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃缴费" andBlock:^(UIAlertAction *action ) {
        if ([action.title isEqualToString:@"好的"]) {
            if ([self.navigationController.viewControllers[0] isKindOfClass:[BalanceHomeViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[0] animated:YES];
            }
            
        }
        
    }  type:@"confirmAndCancel"];
    [self presentViewController:x animated:YES completion:nil];
}
#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getConvenientPaymentInfoFinish:) name:@"GetConvenientPaymentInfoFinish" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifyPayPasswordFinish:) name:@"VerifyPayPasswordFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payConvenientOrderFinish:) name:@"PayConvenientOrderFinish" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
    
    [self updateUI];
    
    if(self.orderInfo && self.cardList.count)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.convenientPayConfirmEngine getPaymentInfo:self.cardList[self.selectedPath.row - 1] andOrderInfo:self.orderInfo];
        
        
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetConvenientPaymentInfoFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifyPayPasswordFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PayConvenientOrderFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
}

@end
